<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/hoem' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item><a href="/">用户管理</a></el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card class="box-card">
      <!-- 搜索与添加区域 -->
      <el-row :gutter="20">
            <el-col :span="7">
            <el-input placeholder="请输入搜索内容" class="input-with-select" v-model="query.query" clearable>
                <el-button slot="append" icon="el-icon-search" @click="getuserList"></el-button>
            </el-input>
            </el-col>
            <el-col :span="5"></el-col>
            <el-button type="primary" @click="dialogVisible = true">添加用户</el-button>
            <!-- 点击添加用户以后弹出的对话框 -->
            <el-dialog title="添加用户" :visible.sync="dialogVisible" width="50%" @close="addFormClosed">
            <!-- 内容主体区域 -->
            <!-- model 数据绑定对象 rules验证规则绑定对象 ref 表单的别名 -->
            <el-form  label-width="70px" class="demo-ruleForm" :model="ruleForm" :rules="rules" ref="addrulesRef" >
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="ruleForm.username"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input v-model="ruleForm.password"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="ruleForm.email"></el-input>
                </el-form-item>
                <el-form-item label="手机" prop="mobile">
                    <el-input v-model="ruleForm.mobile"></el-input>
                </el-form-item>
            </el-form>
            <!-- 底部区域 -->
                <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="adduser">确 定</el-button>
            </span>
            </el-dialog>
        </el-row>
      <!-- 用户列表区域 -->
      <el-table :data="userlist" style="width: 100%" border stripe>
        <el-table-column type="index" label="#"> </el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱"> </el-table-column>
        <el-table-column prop="mobile" label="电话"> </el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <!-- {{ scope.row }} -->
            <el-switch v-model="scope.row.mg_state" @change="userstate(scope.row)"> </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
              <!-- {{scope.row}} -->
            <!-- 修改按钮 -->
            <el-tooltip class="item" effect="dark" content="修改用户信息" placement="top">
                <el-button type="primary" icon="el-icon-edit" size="mini" @click="modifyUser(scope.row.id)"></el-button>
            </el-tooltip>
            <!-- 删除按钮 -->
            <el-tooltip class="item" effect="dark" content="删除用户信息" placement="top">
                <el-button type="danger" icon="el-icon-delete" size="mini" @click="open(scope.row.id)"></el-button>
            </el-tooltip>
            <!-- 分配角色 -->
            <el-tooltip class="item" effect="dark" content="分配角色" placement="top">
                <el-button type="warning" icon="el-icon-setting" size="mini" @click="addRoles(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>  
      </el-table>

      <!-- 分页区域 -->
       <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="query.pagenum"
      :page-sizes="[1, 2, 3, 5]"
      :page-size="query.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
    </el-card>

    <!-- 点击编辑用户信息的按钮后所弹出来的对话框 -->
    <el-dialog title="提示" :visible.sync="dialogVisible1" width="50%" @close="editFormClosed">
        <el-form  label-width="70px" :model="editList" :rules="editrules" ref="editInfoRef" >
            <el-form-item label="用户名" >
                <el-input v-model="editList.username" disabled></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
                <el-input v-model="editList.email"></el-input>
            </el-form-item>
            <el-form-item label="手机" prop="mobile">
                <el-input v-model="editList.mobile"></el-input>
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible1 = false">取 消</el-button>
            <el-button type="primary" @click="modifyuserInfo(editList.id)">确 定</el-button>
        </span>
    </el-dialog>

    <el-dialog title="提示" :visible.sync="dialogVisible3" width="50%" @close="calcleaddRoles">
      <div>
        <p>当前的用户: {{currentRoleInfo.username}}</p>
        <p>当前的角色: {{currentRoleInfo.role_name}}</p>
        <p>分配新角色:
          <el-select v-model="select" placeholder="请选择">
            <el-option v-for="item in allRoleList" :key="item.id" :label="item.roleName" :value="item.id">
            </el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRoleName">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>


<script>
export default {
  data() {
  var checkEmail = (rule, value, cb) => {
      // 验证邮箱的正则表达式
        const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if (regEmail.test(value)) {
        // 合法的邮箱
        return cb()
      }
      cb(new Error('请输入合法的邮箱'))
    }

    // 验证手机号的规则
    var checkMobile = (rule, value, cb) => {
      // 验证手机号的正则表达式
      const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/

      if (regMobile.test(value)) {
        return cb()
      }

      cb(new Error('请输入合法的手机号'))
    }

    return {
      query: {
        query: "",
        pagenum: 1,
        pagesize: 1,
      },
      ruleForm: {
            username: '',
            password: '',
            email: '',
            mobile: ''
        },
         rules: {
            username: [
                { required: true, message: '请输入用户名', trigger: 'blur' },
                { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
            ],
            password: [
                { required: true, message: '请输入密码', trigger: 'blur'  },
                { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
            ],
            email: [
                { required: true, message: '请输入邮箱', trigger: 'blur' },
                { validator: checkEmail}
            ],
            mobile: [
                { required: true, message: '请输入手机号', trigger: 'blur' },
                { validator: checkMobile}
            ]
        },
      userlist: [],
      total: 0,
      search: '',
      dialogVisible:false,
      dialogVisible1: false,
      dialogVisible2: false,
      dialogVisible3: false,
      currentRoleInfo: {},
      currentRoleId: '',
      currentRoleList: [],
      allRoleList: [],
      //保存的是已选中的角色的ID值
      select: '',
      editList: {},
      editrules: {
          email: [
                { required: true, message: '请输入邮箱', trigger: 'blur' },
                { validator: checkEmail, trigger: 'blur' }
            ],
            mobile: [
                { required: true, message: '请输入手机号', trigger: 'blur' },
                { validator: checkMobile, trigger: 'blur'}
            ]
      }
    }
  },
  created() {
    //发送axios请求,获取表单内的数据
    this.getuserList();
  },
  methods: {
    async getuserList() {
      const { data: res } = await this.$http.get("users", {
        params: this.query,
      });
      if (res.meta.status !== 200) return this.$message.error("数据获取失败");
      this.userlist = res.data.users;
      this.total = res.data.total;
      console.log(res.data.users);
      console.log(res.data);
    },
    handleSizeChange(newpagesize) {
        console.log(11);
        this.query.pagesize = newpagesize
        this.getuserList()
    },
    handleCurrentChange(newpagenum) {
        console.log(22);
        this.query.pagenum = newpagenum
        this.getuserList()
    },
    async userstate(val) {
        console.log(val);
        const { data:res } = await this.$http.put(`users/${val.id}/state/${val.mg_state}`)
        //如果操作失败,那么就把用户原来的信息复原
        if (res.meta.status !== 200) {
            val.mg_state = !val.mg_state
            return this.$message.error('更新用户信息失败')
        }
        this.$message.success('更新用户信息成功')
    },
    handleClose(done) {
        this.$confirm('确认关闭？')
          .then(_ => {
            done();
          })
        .catch(_ => {});
    },
    //监听用户对话框关闭事件 重置表单
    addFormClosed() {
        // 拿到表单然后重置表单
        this.$refs.addrulesRef.resetFields()
    },
    adduser() {
        // 表单的预校验
        this.$refs.addrulesRef.validate(async valid => {
            if (!valid) return this.$message.error('请输入正确的信息')
        //验证通过后发送axios请求
            const { data: res }  = await this.$http.post('users', this.ruleForm)
            console.log(res);
            if (res.meta.status !== 201) return this.$message.error('创建用户失败')
            this.$message.success('创建用户成功')
            this.dialogVisible = false
            this.getuserList()
        })
    },
    async modifyUser(id) {
        this.dialogVisible1 = true
        const { data: res } = await this.$http.get(`users/${id}`)
        if (res.meta.status !== 200) return this.$message.error('查询用户信息失败') 
        this.editList = res.data
        console.log(this.editList);
    },
    editFormClosed() {
        // 当点击取消按钮以后,重置表单
        this.dialogVisible1 = false
        this.$refs.editInfoRef.resetFields()
    },
    modifyuserInfo(id) {
        this.$refs.editInfoRef.validate(async valid => {
        if (!valid) return this.$message.error('请输入正确的信息')
        //校验通过
        const { data: res} = await this.$http.put(`users/${id}`, this.editList)
            console.log(res);
            if (res.meta.status !== 200) return this.$message.error('更新用户信息失败') 
            this.$message.success('更新用户信息成功')
            this.dialogVisible1 = false
            this.getuserList()
        })
    },
    //根据ID 删除用户信息
    open(id) {
        this.$confirm('此操作将永久删除该用户信息, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        const {data: res} = await this.$http.delete(`users/${id}`)
        if (res.meta.status !== 200) return this.$message.error('删除用户信息失败')
        this.$message.success('删除用户信息成功')
        this.getuserList()
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
    },
    //分配角色
    async addRoles(role) {
      //显示分配角色的面板
      this.dialogVisible3 = true;
      //把当前角色的ID值保存下来
      // this.currentRoleId = role.id
      // 根据ID 查询用户信息
      // const {data: res} = await this.$http.get(`users/${this.currentRoleId}`)
      // console.log(res);
      this.currentRoleInfo = role
      this.currentRoleId = role.id
      //获取所有角色列表
      const {data: res} = await this.$http.get('roles')
      console.log(res);
      this.allRoleList = res.data
    },  
    calcleaddRoles () {
      this.dialogVisible3 = false
      this.currentRoleInfo = {}
      this.select = ''
    },
    async editRoleName () {
      //首先判断用户是否选择了新的角色名称
      if(!this.select) return this.$message.error('更新用户角色失败')
      console.log(this.currentRoleId);
      const {data: res} = await this.$http.put(`users/${this.currentRoleId}/role`, {rid:this.select})
      if (res.meta.status !== 200) return this.$message.error('更新角色权限失败')
      this.$message.success('更新角色权限成功')
      this.dialogVisible3 = false
  
      this.getuserList()
    }
  },
};
</script>

<style lang="less" scoped>

</style>